package com.tbit.main.service.impl;

import cn.hutool.core.collection.CollUtil;
import com.tbit.common.constant.OperationPlatform;
import com.tbit.common.entity.MachineOpLog;
import com.tbit.main.constant.DaoParamConstant;
import com.tbit.main.controller.interceptor.LoginUserContextHolder;
import com.tbit.main.dao.log.RepairLogDao;
import com.tbit.main.pojo.AccountUser;
import com.tbit.main.pojo.RepairLog;
import com.tbit.main.pojo.RepairLogSta;
import com.tbit.main.service.AccountUserService;
import com.tbit.main.service.GeoreGionService;
import com.tbit.main.service.RepairLogService;
import com.tbit.main.service.RoleService;
import com.tbit.main.util.StringUtil;
import org.apache.commons.collections4.ListUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.*;
import java.util.function.Function;
import java.util.stream.Collectors;

/**
 * 维修记录
 *
 * @author Leon
 * 2020年3月11日 下午7:56:14
 */
@Service("repairLogService")
public class RepairLogServiceImpl implements RepairLogService {
    @Autowired
    private RepairLogDao repairLogDao;
    @Autowired
    private AccountUserService accountUserService;
    @Autowired
    private GeoreGionService georeGionService;
    @Autowired
    private RoleService roleService;
    @Autowired
    private MachineOpLogService machineOpLogService;
    @Autowired
    private RepairPerformanceService repairPerformanceService;

    @Override
    public Integer insert(RepairLog repairLog) {
        Integer result = repairLogDao.insert(repairLog);

        AccountUser accountUser = LoginUserContextHolder.getLoginUser();

        // 插入车辆操作日志
        machineOpLogService.insertSingle(MachineOpLog.builder()
                .accountId(repairLog.getAccountId())
                .machineId(repairLog.getMachineId())
                .machineNO(repairLog.getMachineNO())
                .userCode(repairLog.getUserCode())
                .operation("维修")
                .opUser(accountUser.getName())
                .opUserPhone(accountUser.getPhone())
                .opPlatform(OperationPlatform.MAINTAIN.code)
                .result(true)
                .opTime(LocalDateTime.now())
                .build()
        );

        // 插入维修绩效
        repairPerformanceService.calculateAndInsertPerformance(repairLog);

        return result;
    }

    @Override
    public RepairLog getById(Integer repairLogId) {
        return repairLogDao.getById(repairLogId);
    }

    @Override
    public List<RepairLogSta> groupByTime(Integer accountId, Integer userType, Integer usermainId, String startTime, String endTime, List<Integer> regionId, Integer repairState, Integer machineType) {
        /**查询代理商运维账号*/
        List<Integer> accountUserIds = new ArrayList<>();
        /**判断当前账号是不是运维人员*/
        if (roleService.getRoleCode(userType).equals(1)) {
            accountUserIds.add(usermainId);
        }

        Map<String, Object> params = new HashMap<>();
        params.put(DaoParamConstant.accountId, accountId);
        params.put("accountUserIds", StringUtil.getListString(accountUserIds));
        params.put(DaoParamConstant.startTime, startTime);
        params.put(DaoParamConstant.endTime, endTime);
        params.put("repairState", repairState);
        if (CollUtil.isEmpty(regionId)) {
            params.put("exist", "'exist'");
            regionId = georeGionService.getByAccountUserId(usermainId);
        } else {
            params.put("exist", null);
        }
        params.put("regionId", StringUtil.getListString(regionId));
        params.put("machineType", machineType);

        List<RepairLogSta> rlses = repairLogDao.groupByTime(params);

        List<Integer> userMainIds = rlses.stream().map(RepairLogSta::getAccountUserId).collect(Collectors.toList());
        Map<Integer, AccountUser> accountUserMap = accountUserService.getByIds(userMainIds)
                .stream().collect(Collectors.toMap(AccountUser::getAccountUserId, Function.identity()));

        List<RepairLogSta> mlsefilters = new ArrayList<>();

        for (RepairLogSta rls : rlses) {
            Optional.ofNullable(accountUserMap.get(rls.getAccountUserId()))
                    .ifPresent(au -> {
                        rls.setName(au.getName());
                        rls.setPhone(au.getPhone());
                        rls.setDelFlag(au.getDelFlag());
                        mlsefilters.add(rls);
                    });
        }

        return mlsefilters;
    }

    @Override
    public List<RepairLog> getByTime(Integer accountId, Integer accountUserId, String startTime, String endTime, List<Integer> regionId, Integer repairState, String userCode, Integer machineType) {
        Map<String, Object> params = new HashMap<String, Object>();
        params.put(DaoParamConstant.accountId, accountId);
        params.put("accountUserId", accountUserId);
        params.put(DaoParamConstant.startTime, startTime);
        params.put(DaoParamConstant.endTime, endTime);
        params.put("repairState", repairState);
        params.put("machineType", machineType);
        if (CollUtil.isEmpty(regionId)) {
            params.put("exist", "'exist'");
            regionId = georeGionService.getByAccountUserId(accountUserId);
        } else {
            params.put("exist", null);
        }
        params.put("regionId", StringUtil.getListString(regionId));
        params.put("userCode", userCode);

        return repairLogDao.getByTime(params);
    }

    @Override
    public List<RepairLog> getRepairLogIds(List<Integer> repairLogIds) {
        List<RepairLog> repair = new LinkedList<>();
        List<List<Integer>> repairIds = ListUtils.partition(repairLogIds, 900);
        for (List<Integer> repairId : repairIds) {
            repair.addAll(repairLogDao.getRepairLogIds(StringUtil.getListString(repairId)));
        }
        return repair;
    }

    @Override
    public RepairLog getByFirst(Integer machineId, Integer accountUserId, String time) {

        Map<String, Object> map = new HashMap<>();
        map.put("machineId", machineId);
        map.put("accountUserId", accountUserId);
        map.put("time", time);
        return repairLogDao.getByFirst(map);
    }


}
